package com.buer.storage.service.impl;

import com.buer.storage.dao.UserEntityDao;
import com.buer.storage.entity.UserEntityDO;
import com.buer.storage.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserEntityDao userEntityDao;


    @Override
    public UserEntityDO findByUsername(String username) {
        Map<String,Object> map=new HashMap<>();
        map.put("username",username);
        return userEntityDao.getOne(map);

    }

    //12小时后失效
    private final static int EXPIRE = 12;

    @Override
    public String createToken(UserEntityDO user) {
        //用UUID生成token
        String token = UUID.randomUUID().toString();

        //过期时间
        //LocalDateTime expireTime = now.plusHours(EXPIRE);
        //保存到数据库
        user.setLoginTime(new Date());

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR, EXPIRE);// 24小时制
        Date effectivetime = cal.getTime();

        user.setExpireTime(effectivetime);
        user.setToken(token);

        if(user.getId()!=null&&user.getId()!=0){
            userEntityDao.update(user);
        }else {
            userEntityDao.save(user);
        }

        return token;
    }

    @Override
    public UserEntityDO findByToken(String token) {
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        return userEntityDao.getOne(map);
    }


}

